package com.ll.gulimall.product.service.impl;

import com.ll.gulimall.product.entity.SkuImagesEntity;
import com.ll.gulimall.product.entity.SpuInfoDescEntity;
import com.ll.gulimall.product.service.AttrGroupService;
import com.ll.gulimall.product.service.SkuImagesService;
import com.ll.gulimall.product.service.SpuInfoDescService;
import com.ll.gulimall.product.vo.SkuItemVo;
import com.ll.gulimall.product.vo.SpuItemBaseAttrVo;
import com.ll.gulimall.product.vo.SpuSaleAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ll.common.utils.PageUtils;
import com.ll.common.utils.Query;

import com.ll.gulimall.product.dao.SkuInfoDao;
import com.ll.gulimall.product.entity.SkuInfoEntity;
import com.ll.gulimall.product.service.SkuInfoService;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils findBycondition(Map<String, Object> params) {

        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {

            wrapper.and(w -> {
                w.eq("sku_id", key).or().eq("sku_name", key);

            });
        }
        String catelogId = (String) params.get("catelogId");
        if (catelogId != null && !"0".equals(catelogId)) {

            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (brandId != null && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (min != null) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (max != null && !"0".equals(max)) {


            try {
                BigDecimal bigDecimal = new BigDecimal(max);

                if (bigDecimal.compareTo(BigDecimal.valueOf(0)) == 1) {
                    wrapper.le("price", max);
                }
            } catch (Exception ignored) {
                log.error("max转换失败，不能将错误数据转为bigDecimal");
            }

        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntities;
    }

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 根据Skuid查询sku数据
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
        //1.查询sku基本信息

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity info = this.getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> saleFuture = infoFuture.thenAcceptAsync((res) -> {
            //3.查询sku销售属性组合
            List<SpuSaleAttrGroupVo> saleAttrGroups = this.baseMapper.getSkuSaleAttrGroupBySpuId(res.getSpuId());
            skuItemVo.setSaleAttrGroups(saleAttrGroups);
        }, executor);


        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4.查询spu商品介绍
            SpuInfoDescEntity desc = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(desc);
        }, executor);


        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            //2.查询sku图片信息
            List<SkuImagesEntity> images = skuImagesService.getBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);


        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5.查询sku规格包装
            List<SpuItemBaseAttrVo> spuItemBaseAttrVos = attrGroupService.getAttrGroupWithAttrsBySpuIdCatalogId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setBaseAttrs(spuItemBaseAttrVos);
        }, executor);

        try {
            CompletableFuture.allOf(imgFuture, saleFuture, baseAttrFuture, descFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return skuItemVo;
    }

}